import time
import datetime
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich.box import ROUNDED, DOUBLE, HEAVY
from rich.align import Align

# 初始化控制台
console = Console()

# ------------------------------
# 样式配置
# ------------------------------
class Styles:
    """样式配置类"""
    SUCCESS = "bold green"
    ERROR = "bold red"
    WARNING = "bold yellow"
    INFO = "bold blue"
    HIGHLIGHT = "bold cyan"
    STEP = "bold magenta"
    CONDITION = "bold white"
    ELEMENT = "bold bright_white"
    OPERATION = "bold bright_green"
    SECTION = "bold bright_white"

# ------------------------------
# 定制打印函数
# ------------------------------
class PrintHelper:
    """定制打印助手类"""
    
    @staticmethod
    def print_operation_start(operation_type: str, operation_name: str, icon: str = "🚀"):
        """打印操作开始"""
        console.print()
        console.rule(f"{icon} {operation_type}: {operation_name}", style=Styles.OPERATION)
        console.print()
    
    @staticmethod
    def print_operation_end(operation_type: str, operation_name: str, status: str = "完成", icon: str = "✅"):
        """打印操作结束"""
        status_style = {
            "完成": Styles.SUCCESS,
            "成功": Styles.SUCCESS,
            "失败": Styles.ERROR,
            "取消": Styles.WARNING
        }.get(status, Styles.INFO)
        
        console.print()
        console.rule(f"{icon} {operation_type}: {operation_name} - {status}", style=status_style)
        console.print()
    
    @staticmethod
    def print_step(step_name: str, details: str = "", status: str = "info", icon: str = "📋"):
        """打印步骤信息"""
        status_config = {
            "info": ("ℹ️", Styles.INFO, "blue"),
            "success": ("✅", Styles.SUCCESS, "green"),
            "error": ("❌", Styles.ERROR, "red"),
            "warning": ("⚠️", Styles.WARNING, "yellow"),
            "pending": ("⏳", Styles.INFO, "blue")
        }
        
        status_icon, status_style, border_color = status_config.get(status, ("📋", Styles.INFO, "blue"))
        
        if icon == "auto":
            icon = status_icon
            
        content = Text()
        content.append(f"{icon} ", style=status_style)
        content.append(step_name, style=Styles.STEP)
        if details:
            content.append(f"\n{details}", style=Styles.INFO)
        
        panel = Panel(
            content,
            border_style=border_color,
            box=ROUNDED,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_condition(condition_name: str, condition_type: str, xpath: str, 
                       expected_value: str = None, status: str = "pending"):
        """打印条件信息"""
        status_config = {
            "pending": ("⏳", "等待验证", Styles.INFO, "blue"),
            "success": ("✅", "验证通过", Styles.SUCCESS, "green"),
            "error": ("❌", "验证失败", Styles.ERROR, "red")
        }
        
        status_icon, status_text, status_style, border_color = status_config.get(
            status, ("⏳", "等待验证", Styles.INFO, "blue")
        )
        
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("属性", style=Styles.CONDITION, width=12)
        table.add_column("值", style=Styles.INFO)
        
        table.add_row("状态", f"{status_icon} {status_text}")
        table.add_row("条件类型", f"[{Styles.HIGHLIGHT}]{condition_type}[/{Styles.HIGHLIGHT}]")
        table.add_row("XPath", f"[{Styles.ELEMENT}]{xpath}[/{Styles.ELEMENT}]")
        if expected_value:
            table.add_row("预期值", f"[{Styles.HIGHLIGHT}]{expected_value}[/{Styles.HIGHLIGHT}]")
        
        panel = Panel(
            table,
            title=f"{status_icon} {condition_name}",
            border_style=border_color,
            box=ROUNDED,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_element_info(operation: str, xpath: str, timeout: int = 10, 
                          retry_count: int = 0, details: str = ""):
        """打印元素信息"""
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("属性", style=Styles.CONDITION, width=12)
        table.add_column("值", style=Styles.INFO)
        
        table.add_row("操作类型", f"[{Styles.HIGHLIGHT}]{operation}[/{Styles.HIGHLIGHT}]")
        table.add_row("目标XPath", f"[{Styles.ELEMENT}]{xpath}[/{Styles.ELEMENT}]")
        table.add_row("超时时间", f"{timeout}秒")
        table.add_row("重试次数", f"{retry_count}次")
        if details:
            table.add_row("详细信息", details)
        
        panel = Panel(
            table,
            title="🔍 元素信息",
            border_style="blue",
            box=ROUNDED,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_action_info(action_type: str, target: str, details: str = "", 
                         additional_info: dict = None):
        """打印操作信息"""
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("属性", style=Styles.CONDITION, width=12)
        table.add_column("值", style=Styles.INFO)
        
        table.add_row("操作类型", f"[{Styles.HIGHLIGHT}]{action_type}[/{Styles.HIGHLIGHT}]")
        table.add_row("目标元素", f"[{Styles.ELEMENT}]{target}[/{Styles.ELEMENT}]")
        table.add_row("操作详情", details)
        
        if additional_info:
            for key, value in additional_info.items():
                table.add_row(key, str(value))
        
        icons = {
            "点击": "🖱️",
            "输入": "⌨️",
            "查找": "🔍",
            "等待": "⏳",
            "滚动": "📜"
        }
        
        icon = icons.get(action_type, "⚙️")
        
        panel = Panel(
            table,
            title=f"{icon} 操作信息",
            border_style="cyan",
            box=ROUNDED,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_result(operation: str, step_name: str, status: str, 
                    details: str = "", additional_info: dict = None):
        """打印结果信息"""
        status_config = {
            "success": ("✅", "成功", Styles.SUCCESS, "green", DOUBLE),
            "error": ("❌", "失败", Styles.ERROR, "red", HEAVY),
            "warning": ("⚠️", "警告", Styles.WARNING, "yellow", ROUNDED),
            "info": ("ℹ️", "信息", Styles.INFO, "blue", ROUNDED)
        }
        
        status_icon, status_text, status_style, border_color, box_type = status_config.get(
            status, ("ℹ️", "信息", Styles.INFO, "blue", ROUNDED)
        )
        
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("项目", style=Styles.CONDITION, width=12)
        table.add_column("结果", style=Styles.INFO)
        
        table.add_row("操作类型", operation)
        table.add_row("步骤名称", step_name)
        table.add_row("执行状态", f"{status_icon} {status_text}")
        table.add_row("执行时间", datetime.datetime.now().strftime("%H:%M:%S"))
        
        if details:
            table.add_row("详细信息", details)
            
        if additional_info:
            for key, value in additional_info.items():
                table.add_row(key, str(value))
        
        panel = Panel(
            table,
            title=f"{status_icon} 操作结果",
            border_style=border_color,
            box=box_type,
            padding=(1, 2)
        )
        console.print(panel)
        console.print()
    
    @staticmethod
    def print_progress(description: str, current: int, total: int, 
                      unit: str = "项", width: int = 40):
        """打印进度信息"""
        percent = current / total if total > 0 else 0
        filled_length = int(width * percent)
        bar = "█" * filled_length + "░" * (width - filled_length)
        
        progress_text = Text()
        progress_text.append(f"{description} ", style=Styles.INFO)
        progress_text.append(f"[{bar}] ", style=Styles.HIGHLIGHT)
        progress_text.append(f"{current}/{total}{unit} ({percent:.1%})", style=Styles.SUCCESS)
        
        console.print(progress_text)
    
    @staticmethod
    def print_status(description: str, status: str = "处理中", icon: str = "⏳"):
        """打印状态信息"""
        status_style = {
            "处理中": Styles.INFO,
            "完成": Styles.SUCCESS,
            "错误": Styles.ERROR,
            "警告": Styles.WARNING
        }.get(status, Styles.INFO)
        
        status_text = Text()
        status_text.append(f"{icon} ", style=status_style)
        status_text.append(description, style=Styles.INFO)
        status_text.append(f" - {status}", style=status_style)
        
        console.print(status_text)
    
    @staticmethod
    def print_divider(text: str = "", style: str = Styles.INFO):
        """打印分隔线"""
        if text:
            console.rule(text, style=style)
        else:
            console.print("─" * 80, style="dim")
    
    @staticmethod
    def print_warning(message: str, details: str = ""):
        """打印警告信息"""
        warning_text = Text()
        warning_text.append("⚠️ 警告: ", style=Styles.WARNING)
        warning_text.append(message, style=Styles.WARNING)
        if details:
            warning_text.append(f"\n{details}", style=Styles.INFO)
        
        panel = Panel(
            warning_text,
            border_style="yellow",
            box=ROUNDED,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_error(message: str, details: str = ""):
        """打印错误信息"""
        error_text = Text()
        error_text.append("❌ 错误: ", style=Styles.ERROR)
        error_text.append(message, style=Styles.ERROR)
        if details:
            error_text.append(f"\n{details}", style=Styles.INFO)
        
        panel = Panel(
            error_text,
            border_style="red",
            box=HEAVY,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_success(message: str, details: str = ""):
        """打印成功信息"""
        success_text = Text()
        success_text.append("✅ 成功: ", style=Styles.SUCCESS)
        success_text.append(message, style=Styles.SUCCESS)
        if details:
            success_text.append(f"\n{details}", style=Styles.INFO)
        
        panel = Panel(
            success_text,
            border_style="green",
            box=DOUBLE,
            padding=(0, 1)
        )
        console.print(panel)
    
    @staticmethod
    def print_info(message: str, details: str = ""):
        """打印信息"""
        info_text = Text()
        info_text.append("ℹ️ 信息: ", style=Styles.INFO)
        info_text.append(message, style=Styles.INFO)
        if details:
            info_text.append(f"\n{details}", style=Styles.INFO)
        
        panel = Panel(
            info_text,
            border_style="blue",
            box=ROUNDED,
            padding=(0, 1)
        )
        console.print(panel)

# ------------------------------
# 使用示例
# ------------------------------
if __name__ == "__main__":
    # 演示所有打印函数的使用
    
    # PrintHelper.print_operation_start("元素查找", "查找登录输入框")
    
    # PrintHelper.print_step("步骤1: 验证页面加载", "检查页面标题是否为登录页", "info")
    
    # PrintHelper.print_condition(
    #     "前置条件验证", 
    #     "ElementIsVisible", 
    #     "//div[@class='login-container']",
    #     status="pending"
    # )
    
    # # 模拟条件验证完成
    # time.sleep(1)
    # PrintHelper.print_condition(
    #     "前置条件验证", 
    #     "ElementIsVisible", 
    #     "//div[@class='login-container']",
    #     status="success"
    # )
    
    # PrintHelper.print_element_info(
    #     "查找元素",
    #     "//input[@id='username']",
    #     timeout=10,
    #     retry_count=3,
    #     details="查找用户名输入框"
    # )
    
    # PrintHelper.print_progress("查找进度", 2, 5, "个元素")
    
    # PrintHelper.print_status("正在查找元素", "处理中")
    
    # # 模拟查找完成
    # time.sleep(1)
    # PrintHelper.print_status("元素查找", "完成", "✅")
    
    # PrintHelper.print_action_info(
    #     "输入",
    #     "//input[@id='username']",
    #     "输入用户名",
    #     {"输入内容": "testuser", "清空输入": True}
    # )
    
    # PrintHelper.print_divider("操作结果")
    
    # PrintHelper.print_result(
    #     "键盘输入",
    #     "输入用户名",
    #     "success",
    #     "用户名输入成功",
    #     {"目标元素": "//input[@id='username']", "输入内容": "testuser"}
    # )
    
    # PrintHelper.print_operation_end("元素查找", "查找登录输入框", "成功")
    
    # # 演示其他信息类型
    # PrintHelper.print_warning("元素未立即找到", "将在2秒后重试")
    # PrintHelper.print_error("元素查找失败", "已达到最大重试次数")
    # PrintHelper.print_success("操作完成", "所有步骤执行成功")
    # PrintHelper.print_info("提示信息", "这是普通信息提示")
    PrintHelper.print_info(message="提示信息", details="这是普通信息提示")